package com.compass.network.manager

import com.compass.framework.constant.BASE_URL
import com.compass.framework.helper.CompassAppHelper
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.NetworkUtil
import com.compass.network.error.ERROR
import com.compass.network.error.NoNetWorkException
import com.compass.network.interceptor.HeaderInterceptor
import com.compass.network.interceptor.PublicParameterInterceptor
import com.compass.network.interceptor.TokenInterceptor
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit


/**
 *
 * @desc  网络请求管理类
 */
object HttpManager {
    private val mRetrofit: Retrofit


    init {
        mRetrofit = Retrofit.Builder()
                .client(initOkHttpClient())
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
    }

    /**
     * 获取 apiService
     */
    fun <T> create(apiService: Class<T>): T {
        return mRetrofit.create(apiService)
    }

    /**
     * 初始化OkHttp
     */
    private fun initOkHttpClient(): OkHttpClient {
        val build = OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
        // 添加参数拦截器
        val interceptors = mutableListOf<Interceptor>()
        build.addInterceptor(HeaderInterceptor())// 头信息拦截器
        build.addInterceptor(PublicParameterInterceptor())//公共参数
        build.addInterceptor(TokenInterceptor())//token拦截器
//        build.addInterceptor(TokenApiInterceptor())//token拦截器


        //日志拦截器
        val logInterceptor = HttpLoggingInterceptor { message: String ->
            LogUtil.d("http_data:$message")
        }
        if (CompassAppHelper.isDebug()) {
            logInterceptor.level = HttpLoggingInterceptor.Level.BODY
        } else {
            logInterceptor.level = HttpLoggingInterceptor.Level.BASIC
        }
        build.addInterceptor(logInterceptor)
        //网络状态拦截
        build.addInterceptor(object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                if (NetworkUtil.isConnected(CompassAppHelper.getApplication())) {
                    val request = chain.request()
                    return chain.proceed(request)
                } else {
                    throw NoNetWorkException(ERROR.NETWORD_ERROR)
                }
            }
        })
        return build.build()
    }
}